package com.xmh.reptile.service;

import cn.hutool.core.io.FileUtil;
import com.xmh.reptile.util.RedisMockUtil;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NovelKkknbService {

    public static int errorCount = 0;

    public static final String key = "万古至尊";

    public static long newPageNumber = Long.parseLong(String.valueOf(RedisMockUtil.get(key) == null ? 0 : RedisMockUtil.get(key)));

    public static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

    public static void wgzz() throws InterruptedException {
        StringBuilder sb = new StringBuilder();

        for (int i = 1; i < 19; i++) {
            try {
                String url = "https://m.kkknb.com/107/107210";

                if (i != 1) {
                    url += "_" + i;
                }
                Document doc = Jsoup.connect(url).get();

                Elements list = doc.select("#zjlb > ul > li > a");
                for (Element element : list) {
                    String href = element.attr("href");

                    if (StringUtils.isEmpty(href)) {
                        continue;
                    }

                    String title = element.html();

                    String number = extractNumbersFromString(title);

                    if (Integer.parseInt(number) < 221) {
                        continue;
                    }
                    System.out.println(title);

                    sb.append("\n\n====== ").append(title).append(" =====\n\n");

                    String detailUrl = "https://m.kkknb.com" + href;
                    Document detailDoc = callAgain(detailUrl);

                    Element select = detailDoc.getElementById("chaptercontent");

                    String text = textHandle(select.html());

                    sb.append(text);

                    Elements nextPageElement = detailDoc.select("#chaptercontent .Readpage");
                    if (nextPageElement != null) {
                        Element nextPage = nextPageElement.get(0);
                        String nextPageHtml = nextPage.html();
                        String pageNumber = extractNumbersFromString(nextPageHtml);

                        String substring = pageNumber.substring(0, 1);
                        String substring2 = pageNumber.substring(1, 2);

                        if (Integer.parseInt(substring) < Integer.parseInt(substring2)) {
                            for (int j = Integer.parseInt(substring) + 1; j <= Integer.parseInt(substring2); j++) {
                                detailUrl += "_" + j + ".shtml";
                                detailUrl = detailUrl.replace("书号", "");
                                detailUrl = detailUrl.replace("内页", "");
                                detailUrl = detailUrl.replace("tb", "");
                                detailUrl = detailUrl.replace("sy", "/");
                                detailUrl = detailUrl.replace("nau", "/");
                                detailDoc = callAgain(detailUrl);
                                select = detailDoc.getElementById("chaptercontent");
                                text = textHandle(select.html());
                                sb.append(text);
                            }
                        }
                    }
                    Thread.sleep(1000);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotEmpty(sb.toString())) {
            FileUtil.appendString(sb.toString(), new File("C:\\Users\\12425\\OneDrive\\桌面\\test" + simpleDateFormat.format(new Date()) + ".txt"), "UTF-8");
            RedisMockUtil.set(key, newPageNumber);
        }
    }

    public static String extractNumbersFromString(String str) {
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (Character.isDigit(ch)) {
                builder.append(ch);
            }
        }

        return builder.toString();
    }

    private static Document callAgain(String url) throws InterruptedException {
        try {
//            https://m.kkknb.com/tb107%E4%B9%A6%E5%8F%B7sy107210%E5%86%85%E9%A1%B5nau43873712
            url = url.replace("书号", "%E4%B9%A6%E5%8F%B7");
            url = url.replace("内页", "%E5%86%85%E9%A1%B5");
            Document doc = Jsoup.connect(url).get();
            errorCount = 0;
            System.out.println("success get url !!!");
            return doc;
        } catch (Exception e) {
            System.out.println("have a error, errorCount: " + (errorCount + 1));
            if (errorCount++ > 10) {
                throw new RuntimeException();
            }
            Thread.sleep(5000);
            return callAgain(url);
        }
    }

    private static String textHandle(String text) {
        String result = text.replace("&nbsp;", "");
        result = result.replace("<p class=\"Readpage\">(第1/2页)本章未完，请点击↓↓↓继续阅读</p>", "");
        result = result.replace("<p class=\"Readpage\">(第2/2页)本章未完，请点击↓↓↓继续阅读</p>", "");
        result = result.replace("<br>", "");
        result = result.replace("&amp;", "");
        return result;
    }

}
